import { HubConnectionBuilder, LogLevel } from 'signalr-uni'
import { ref, onUnmounted } from 'vue'

const baseUrl = 'https://localhost:7214/'
import { useUserStore } from '../stores/user'
const userStore = useUserStore()

export function useSignalR(hub="chatHub") {
  // 响应式状态
  const connectionState = ref('Disconnected')
  const error = ref(null)
  const subscriptions = new Map()
  // 创建连接实例
  const connection = new HubConnectionBuilder()
    .withUrl(baseUrl+hub, {
        accessTokenFactory: () => userStore.token
    })
    .withAutomaticReconnect({
      nextRetryDelayInMilliseconds: retryContext => {
        return Math.min(retryContext.previousRetryCount * 1000, 10000)
      }
    })
    .configureLogging(LogLevel.Warning)
    .build()

  // 更新连接状态
  const updateState = () => {
    connectionState.value = connection.state
  }

  // 连接状态监听
  connection.onclose(() => {
    updateState()
    console.log('连接已关闭')
  })

  connection.onreconnecting(() => {
    updateState()
    console.log('正在重连...')
  })

  connection.onreconnected(() => {
    updateState()
    console.log('重连成功')
  })

  // 启动连接
  const start = async () => {
    try {
      await connection.start()
      updateState()
      console.log('SignalR 连接成功')
    } catch (err) {
      error.value = err
      console.error('SignalR 连接失败:', err)
      setTimeout(() => start(), 5000) // 5秒后重试
    }
  }
  
  const invoke = (conversationId,content)=>{
	  connection.invoke("SendMessage",conversationId,userStore.userId,content).catch(err=>{
		  console.log(err);
	  })
  }
  
  // const on = (method,callback)=>{
	 //  connection.on(method,(...args) =>{
		//   callback(...args)
	 //  })
  // }
  
  const on = (eventName, callback)=>{
	  const handler = (...args) => callback(...args)
	        subscriptions.set(eventName, handler)
	        connection.on(eventName, handler)
			console.log('监听'+eventName);
  }
  const off = (eventName)=>{
	  const handler = subscriptions.get(eventName)
	  if (handler) {
	          connection.off(eventName, handler)
	          subscriptions.delete(eventName)
			  console.log('取消监听'+eventName);
	        }
  }

  // 停止连接
  const stop = async () => {
    try {
      await connection.stop()
      updateState()
      console.log('SignalR 连接已关闭')
    } catch (err) {
      error.value = err
      console.error('关闭 SignalR 失败:', err)
    }
  }

  // 组件卸载时自动关闭连接
  onUnmounted(() => {
    stop()
  })

  return {
    // 响应式状态
    connectionState,
    error,
    
    // 操作方法
    start,
    stop,
    
    // 消息处理
    // on: connection.on.bind(connection),
	on,
    off,
    // 调用方法
    // invoke: connection.invoke.bind(connection),
    invoke,
    // 原生连接实例（按需暴露）
    rawConnection: connection
  }
}
